﻿using System.Reflection;

namespace BlazorAdmin.Tcp.Protocol
{
    /// <summary>
    /// 枚举扩展类
    /// </summary>
    public class DataCode
    {
        public static Dictionary<TcpPolicy, DataTypeAttribute> GetMappings()
        {
            Dictionary<TcpPolicy, DataTypeAttribute> mapping;
            Type type = typeof(TcpPolicy);
            Type dataType = typeof(DataTypeAttribute);
            string[] codes = Enum.GetNames<TcpPolicy>();

            if (null == codes || codes.Length < 1)
            {
                mapping = new();
                return mapping;
            }

            mapping = new(codes.Length);
            foreach (string code in codes)
            {
                MemberInfo[]? members = type.GetMember(code);
                if (null == members || members.Length < 1 || !Enum.TryParse(code, true, out TcpPolicy dataCode))
                    continue;
                MemberInfo memberInfo = members[0];
                if (memberInfo.GetCustomAttribute(dataType, false) is DataTypeAttribute attr && null != attr.DataType)
                    mapping[dataCode] = attr;
            }

            return mapping;
        }
    }
}
